package artid.com.arttogoa.db;



import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.StreamCorruptedException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import android.content.Context;

/**
 * ClassName:TokenKeeper <br/>
 * Date: 2013-11-1 上午11:02:25 <br/>
 * 
 * @author hushuan
 * @version
 * @since JDK 1.6
 * @see
 */
public class DataKeeper {

	public static void keepSerializable(Context context, Serializable value) {
		ObjectOutputStream oos = null;
		String fileName = value.getClass().getSimpleName();
		clear(context, value.getClass());
		try {
			FileOutputStream fos = context.openFileOutput(fileName,
					Context.MODE_PRIVATE);
			GZIPOutputStream gos = new GZIPOutputStream(fos);
			oos = new ObjectOutputStream(gos);
			oos.writeObject(value);
			oos.flush();
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
		} finally {
			try {
				if (null != oos) {
					oos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static boolean clear(Context context,
			Class<? extends Serializable> cls) {
		String fileName = cls.getSimpleName();
		if (context != null)
			return context.deleteFile(fileName);
		else
			return false;
	}

	public static Serializable readSerializable(Context context,
			Class<? extends Serializable> cls) {
		Serializable value = null;
		String fileName = cls.getSimpleName();
		ObjectInputStream ois = null;
		try {
			FileInputStream fis = context.openFileInput(fileName);
			GZIPInputStream gis = new GZIPInputStream(fis);
			ois = new ObjectInputStream(gis);
			value = (Serializable) ois.readObject();
		} catch (FileNotFoundException e) {
		} catch (StreamCorruptedException e) {
		} catch (IOException e) {
		} catch (ClassNotFoundException e) {
		} finally {
			try {
				if (null != ois) {
					ois.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return value;
	}
}
